package com.zhaopin.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicAgency {

    static interface MyInterface {
        void test();
    }

    static class MyInterfaceImpl implements MyInterface{

        @Override
        public void test() {
            System.out.println("run real method!");
        }
    }

    static class InvocationHandlerImpl implements InvocationHandler {

        private Object realObject;

        public InvocationHandlerImpl(Object realObject) {
            this.realObject = realObject;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("before");
            Object results = method.invoke(realObject, args);
            System.out.println("after");
            return results;
        }
    }

    public static void main(String[] args) {
        MyInterface myInterface = new MyInterfaceImpl();
        InvocationHandler invocationHandler = new InvocationHandlerImpl(myInterface);

        MyInterface myInterface1 = (MyInterface)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{MyInterface.class}, invocationHandler);
        myInterface1.test();


    }
}
